<template>
    <div>
        <Upload ref="upload" action="/api/upload/file" 
            :format="format"
            :on-format-error="handleFormatError"
            :default-file-list="defaultList" 
            :on-remove="handleRemove" 
            :on-success="handleSuccess"
            :on-preview="viewImage"
            :before-upload="checkSingle"
            :max-size="8000">
        <Button type="ghost" icon="ios-cloud-upload-outline" :disabled="disabled">上传图片</Button>
        </Upload>
        <Modal id="viewImageModal" title="查看图片" v-model="visible">
            <img :src="defaultList[0].url" v-if="visible" style="width: 100%">
        </Modal>
    </div>
    
</template>
<script>
    export default {
        name: 'UploadSingleFile',
        props: {
            value: {
                type: Array
            },
            format: {
                type: Array,
                default: ['jpg','jpeg','png','doc','docx','txt']
            },
            disabled: {
                type: Boolean,
                default: false
            }
        },
        data () {
            return {
                visible:false
            }
        },
        computed: {
            defaultList() {
                return this.value;
            }
        },
        methods: {
            handleSuccess (res, file) {
                if(res.status == 10000) {
                    if(res.list.length > 0) 
                    {
                        this.value.push(res.list[0]);
                    }
                }else {
                    this.$refs.upload.fileList.splice(this.$refs.upload.fileList.length-1, 1);
                    this.$Message.error(res.message);
                }
            },
            handleRemove (file) {
                const fileList = this.$refs.upload.fileList;
                var index = fileList.indexOf(file);
                this.value.splice(index, 1);
                // this.api.post("upload/delete", { id: file.id }, res => {
                // });
            },
            handleFormatError (file) {
                this.$Notice.warning({
                    title: '错误文件类型',
                    desc: '文件' + file.name + ' 格式错误，支持文件格式为' + this.format.join(",")
                });
            },
            checkSingle(){
                console.log(this.$refs.upload.fileList);
                const check = this.$refs.upload.fileList < 1;
                if(!check){
                    this.$Notice.warning({
                        title: '提示',
                        desc:"只能上传一张图片,修改前请删除原图片"
                    });
                }
                return check;
            },
            viewImage(file){
                this.visible = true;
            }
        }
    }
</script>
<style>
    #viewImageModal{
        position: absolute;
        z-index: 10;
    }
</style>
